/*
 * INSANE - Interactive Structural Analysis Environment
 *
 * Copyright (C) 2003-2005
 * Universidade Federal de Minas Gerais
 * Escola de Engenharia
 * Departamento de Engenharia de Estruturas
 * 
 * Author's email :    insane@dees.ufmg.br
 * Author's website :  http://www.dees.ufmg.br/insane
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package br.ufmg.dees.insane.persistence;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.text.DecimalFormat;
import java.util.Observable;
import java.util.Observer;

import br.ufmg.dees.insane.model.femModel.Model;
import br.ufmg.dees.insane.solution.EquilibriumPath;
import br.ufmg.dees.insane.solution.Solution;
import br.ufmg.dees.insane.util.LoadCombination;

/**
 * A class representing PersistenceAsObject
 * 
 * @author CENOURA!!!
 * @since 25/09/2006
 */
public class PersistenceAsInsane implements Persistence, Observer {
	
	public static String path = "";
	public static String fileName = "model";
	public static String simpleName = "model";
    private StepModel stepModel;
    private int q = 0;
	
	/** The Model of this persistence. */
	protected Model model;
	
	/** The Solution of this persistence. */
	protected Solution solution;

	/**
	 * Returns the Model of this application.
	 * @return The Model of this application.
	 */
	public Model getModel() {
		return (model);
	}
	
	/**
	 * Sets the Model of this application.
	 * @param a The Model of this application.
	 */
	public void setModel(Model m) {
		model = m;
	}

	/**
	 * Returns the Solution of this application.
	 * @return The Solution of this application.
	 */
	public Solution getSolution() {
		return (solution);
	}

	/**
	 * Sets the Solution of this application.
	 * @param a The Solution of this application.
	 */
	public void setSolution(Solution s) {
		solution = s;
	}
	
	/* (non-Javadoc)
	 * @see br.ufmg.dees.insane.persistence.Persistence#fillInsaneFromFile(java.lang.String)
	 */
	public void fillInsaneFromFile(String file) {
		try{
			FileInputStream fin = new FileInputStream(file);
			ObjectInputStream ois = new ObjectInputStream(fin);
			Solution s = (Solution) ois.readObject();
			ois.close();
			fin.close();
			this.setSolution(s);
			this.setModel(this.getSolution().getAssembler().getModel());
            double loadFactor=0;
            int stepLabel = 0;
            if(s instanceof EquilibriumPath){
                loadFactor  = ((EquilibriumPath)s).getStep().getLoadFactorTotal();
                stepLabel = ((EquilibriumPath)s).getStep().getLabel();
            }else{
                loadFactor =0;
                stepLabel = 0;
            }
            stepModel = new StepModel(this.getModel(),loadFactor);
            stepModel.setStepLabel(stepLabel);
            
		}
		catch (IOException e) {
			e.printStackTrace();
		}
		catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	/* (non-Javadoc)
	 * @see br.ufmg.dees.insane.persistence.Persistence#fillFileFromModel()
	 */
	public void fillFileFromModel() {
		try{
            FileOutputStream serialStream = new FileOutputStream(fileName);
            ObjectOutputStream stream = new ObjectOutputStream(serialStream);
            double loadFactor=0;
            if(this.getSolution() instanceof EquilibriumPath){
                loadFactor  = ((EquilibriumPath)this.getSolution()).getStep().getLoadFactorTotal();
            }else{
                loadFactor =0;
            }
            this.setStepModel(new StepModel(this.getModel(),loadFactor));
            stream.writeObject(this.getStepModel());
            serialStream.flush();
            DecimalFormat fmt = new DecimalFormat();
			fmt.applyPattern("000");
			System.out.println("File \"" + fileName + "\" successfully saved.\n");
        }catch (IOException e){
        	e.printStackTrace();
        }

	}
	
	/*
	 * (non-Javadoc)
	 * 
	 * @see java.util.Observer#update(java.util.Observable, java.lang.Object)
	 */
	public void update(Observable o, Object arg) {
		if(path.equals("")){
			File newdir0 = new File("RESULTS");
			if (newdir0.mkdir());
			File newdir1 = new File(newdir0.getAbsolutePath() + File.separator + solution.getLabel());
			if (newdir1.mkdir());
			File newdir = new File(newdir1.getAbsolutePath() + File.separator + "Insane");
			if (newdir.mkdir());
			
			if (solution.getClass().getName().equals(
			"br.ufmg.dees.insane.solution.EquilibriumPath")) {
				DecimalFormat fmt = new DecimalFormat();
				fmt.applyPattern("000");
				fileName = newdir.getAbsolutePath()
				+ File.separator + solution.getLabel()
				+ "-STEP-"
				+ fmt.format(((EquilibriumPath) solution).getStep()
						.getLabel()) + ".isn";
			}
			
			if (solution.getClass().getName().equals(
					"br.ufmg.dees.insane.solution.SteadyState")) {
				File newdir2 = new File(newdir1.getAbsolutePath() + File.separator
						+ "Insane");
				if (newdir2.mkdir());
				fileName = newdir.getAbsolutePath()
								+ File.separator + solution.getLabel()
								+ "-LoadComb" + ((LoadCombination)model.getLoadCombinationsList().get(q)).getLabel()+".isn";
				q++;
			}
			
			this.fillFileFromModel();
		}else{
			File newdirPath = new File(path);
			if (newdirPath.mkdir()) {
				;
			}
			
			File newdir0 = new File(newdirPath.getAbsolutePath()+ File.separator+"RESULTS");
			if (newdir0.mkdir()) {
				;
			}
			File newdir1 = new File(newdir0.getAbsolutePath() + File.separator + simpleName);
			if (newdir1.mkdir()) {
				;
			}
			File newdir = new File(newdir1.getAbsolutePath() + File.separator + "InsaneBinObj");
			if (newdir.mkdir()) {
				;
			}
			if (solution.getClass().getName().equals(
			"br.ufmg.dees.insane.solution.EquilibriumPath")) {
				DecimalFormat fmt = new DecimalFormat();
				fmt.applyPattern("000");
				fileName = newdir.getAbsolutePath()
				+ File.separator + simpleName
				+ "-STEP-"
				+ fmt.format(((EquilibriumPath) solution).getStep()
						.getLabel()) + ".isn";
			}
			
			if (solution.getClass().getName().equals(
					"br.ufmg.dees.insane.solution.SteadyState")) {
				File newdir2 = new File(newdir1.getAbsolutePath() + File.separator
						+ "Insane");
				if (newdir2.mkdir());
				fileName = newdir.getAbsolutePath()
								+ File.separator + simpleName
								+ "-LoadComb" + ((LoadCombination)model.getLoadCombinationsList().get(q)).getLabel()+".isn";
				q++;
			}
			
			this.fillFileFromModel();
		}
		

	}

    public StepModel getStepModel() {
        return stepModel;
    }

    public void setStepModel(StepModel stepModel) {
        this.stepModel = stepModel;
    }

}
